blob: 3519b000a33ff844ccda05bdb0567b517919955c [file] [log] [blame]
Jun Bum Lim0c990072017-11-03 20:41:16 +00001//===- CallSiteSplitting.cpp ----------------------------------------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Jun Bum Lim0c990072017-11-03 20:41:16 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This file implements a transformation that tries to split a call-site to pass
10// more constrained arguments if its argument is predicated in the control flow
11// so that we can expose better context to the later passes (e.g, inliner, jump
12// threading, or IPA-CP based function cloning, etc.).
13// As of now we support two cases :
14//
Florian Hahn7e932892017-12-23 20:02:26 +000015// 1) Try to a split call-site with constrained arguments, if any constraints
16// on any argument can be found by following the single predecessors of the
17// all site's predecessors. Currently this pass only handles call-sites with 2
18// predecessors. For example, in the code below, we try to split the call-site
19// since we can predicate the argument(ptr) based on the OR condition.
Jun Bum Lim0c990072017-11-03 20:41:16 +000020//
21// Split from :
22// if (!ptr || c)
23// callee(ptr);
24// to :
25// if (!ptr)
26// callee(null) // set the known constant value
27// else if (c)
28// callee(nonnull ptr) // set non-null attribute in the argument
29//
30// 2) We can also split a call-site based on constant incoming values of a PHI
31// For example,
32// from :
33// Header:
34// %c = icmp eq i32 %i1, %i2
35// br i1 %c, label %Tail, label %TBB
36// TBB:
37// br label Tail%
38// Tail:
39// %p = phi i32 [ 0, %Header], [ 1, %TBB]
40// call void @bar(i32 %p)
41// to
42// Header:
43// %c = icmp eq i32 %i1, %i2
44// br i1 %c, label %Tail-split0, label %TBB
45// TBB:
46// br label %Tail-split1
47// Tail-split0:
48// call void @bar(i32 0)
49// br label %Tail
50// Tail-split1:
51// call void @bar(i32 1)
52// br label %Tail
53// Tail:
54// %p = phi i32 [ 0, %Tail-split0 ], [ 1, %Tail-split1 ]
55//
56//===----------------------------------------------------------------------===//
57
58#include "llvm/Transforms/Scalar/CallSiteSplitting.h"
59#include "llvm/ADT/Statistic.h"
60#include "llvm/Analysis/TargetLibraryInfo.h"
Florian Hahnb4e3bad2018-02-14 13:59:12 +000061#include "llvm/Analysis/TargetTransformInfo.h"
David Blaikie31b98d22018-06-04 21:23:21 +000062#include "llvm/Transforms/Utils/Local.h"
Jun Bum Lim0c990072017-11-03 20:41:16 +000063#include "llvm/IR/IntrinsicInst.h"
64#include "llvm/IR/PatternMatch.h"
65#include "llvm/Support/Debug.h"
66#include "llvm/Transforms/Scalar.h"
67#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Florian Hahnb4e3bad2018-02-14 13:59:12 +000068#include "llvm/Transforms/Utils/Cloning.h"
Jun Bum Lim0c990072017-11-03 20:41:16 +000069
70using namespace llvm;
71using namespace PatternMatch;
72
73#define DEBUG_TYPE "callsite-splitting"
74
75STATISTIC(NumCallSiteSplit, "Number of call-site split");
76
Florian Hahnb4e3bad2018-02-14 13:59:12 +000077/// Only allow instructions before a call, if their CodeSize cost is below
78/// DuplicationThreshold. Those instructions need to be duplicated in all
79/// split blocks.
80static cl::opt<unsigned>
81 DuplicationThreshold("callsite-splitting-duplication-threshold", cl::Hidden,
82 cl::desc("Only allow instructions before a call, if "
83 "their cost is below DuplicationThreshold"),
84 cl::init(5));
85
Florian Hahnc6c89bf2018-01-16 22:13:15 +000086static void addNonNullAttribute(CallSite CS, Value *Op) {
Jun Bum Lim0c990072017-11-03 20:41:16 +000087 unsigned ArgNo = 0;
88 for (auto &I : CS.args()) {
89 if (&*I == Op)
90 CS.addParamAttr(ArgNo, Attribute::NonNull);
91 ++ArgNo;
92 }
93}
94
Florian Hahnc6c89bf2018-01-16 22:13:15 +000095static void setConstantInArgument(CallSite CS, Value *Op,
96 Constant *ConstValue) {
Jun Bum Lim0c990072017-11-03 20:41:16 +000097 unsigned ArgNo = 0;
98 for (auto &I : CS.args()) {
Xin Tong8edff272018-04-23 20:09:08 +000099 if (&*I == Op) {
100 // It is possible we have already added the non-null attribute to the
101 // parameter by using an earlier constraining condition.
102 CS.removeParamAttr(ArgNo, Attribute::NonNull);
Jun Bum Lim0c990072017-11-03 20:41:16 +0000103 CS.setArgument(ArgNo, ConstValue);
Xin Tong8edff272018-04-23 20:09:08 +0000104 }
Jun Bum Lim0c990072017-11-03 20:41:16 +0000105 ++ArgNo;
106 }
107}
108
Florian Hahn2a266a32017-11-18 18:14:13 +0000109static bool isCondRelevantToAnyCallArgument(ICmpInst *Cmp, CallSite CS) {
110 assert(isa<Constant>(Cmp->getOperand(1)) && "Expected a constant operand.");
111 Value *Op0 = Cmp->getOperand(0);
112 unsigned ArgNo = 0;
113 for (CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end(); I != E;
114 ++I, ++ArgNo) {
115 // Don't consider constant or arguments that are already known non-null.
116 if (isa<Constant>(*I) || CS.paramHasAttr(ArgNo, Attribute::NonNull))
117 continue;
118
119 if (*I == Op0)
120 return true;
121 }
122 return false;
123}
124
Florian Hahnc6c89bf2018-01-16 22:13:15 +0000125typedef std::pair<ICmpInst *, unsigned> ConditionTy;
126typedef SmallVector<ConditionTy, 2> ConditionsTy;
127
Florian Hahnbeda7d52017-12-13 03:05:20 +0000128/// If From has a conditional jump to To, add the condition to Conditions,
129/// if it is relevant to any argument at CS.
Florian Hahnc6c89bf2018-01-16 22:13:15 +0000130static void recordCondition(CallSite CS, BasicBlock *From, BasicBlock *To,
131 ConditionsTy &Conditions) {
Florian Hahnbeda7d52017-12-13 03:05:20 +0000132 auto *BI = dyn_cast<BranchInst>(From->getTerminator());
133 if (!BI || !BI->isConditional())
134 return;
Florian Hahn2a266a32017-11-18 18:14:13 +0000135
Florian Hahnbeda7d52017-12-13 03:05:20 +0000136 CmpInst::Predicate Pred;
137 Value *Cond = BI->getCondition();
138 if (!match(Cond, m_ICmp(Pred, m_Value(), m_Constant())))
139 return;
140
141 ICmpInst *Cmp = cast<ICmpInst>(Cond);
142 if (Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE)
143 if (isCondRelevantToAnyCallArgument(Cmp, CS))
144 Conditions.push_back({Cmp, From->getTerminator()->getSuccessor(0) == To
145 ? Pred
146 : Cmp->getInversePredicate()});
Florian Hahn2a266a32017-11-18 18:14:13 +0000147}
148
Florian Hahnbeda7d52017-12-13 03:05:20 +0000149/// Record ICmp conditions relevant to any argument in CS following Pred's
Xin Tongd83c8832018-04-13 04:35:38 +0000150/// single predecessors. If there are conflicting conditions along a path, like
Florian Hahn505091a2018-11-14 10:04:30 +0000151/// x == 1 and x == 0, the first condition will be used. We stop once we reach
152/// an edge to StopAt.
Florian Hahnc6c89bf2018-01-16 22:13:15 +0000153static void recordConditions(CallSite CS, BasicBlock *Pred,
Florian Hahn505091a2018-11-14 10:04:30 +0000154 ConditionsTy &Conditions, BasicBlock *StopAt) {
Florian Hahnbeda7d52017-12-13 03:05:20 +0000155 BasicBlock *From = Pred;
156 BasicBlock *To = Pred;
Florian Hahn212afb92018-01-26 10:36:50 +0000157 SmallPtrSet<BasicBlock *, 4> Visited;
Florian Hahn505091a2018-11-14 10:04:30 +0000158 while (To != StopAt && !Visited.count(From->getSinglePredecessor()) &&
Florian Hahnbeda7d52017-12-13 03:05:20 +0000159 (From = From->getSinglePredecessor())) {
160 recordCondition(CS, From, To, Conditions);
Florian Hahn212afb92018-01-26 10:36:50 +0000161 Visited.insert(From);
Florian Hahnbeda7d52017-12-13 03:05:20 +0000162 To = From;
163 }
164}
Jun Bum Lim0c990072017-11-03 20:41:16 +0000165
Florian Hahnc6c89bf2018-01-16 22:13:15 +0000166static void addConditions(CallSite CS, const ConditionsTy &Conditions) {
Florian Hahnbeda7d52017-12-13 03:05:20 +0000167 for (auto &Cond : Conditions) {
168 Value *Arg = Cond.first->getOperand(0);
169 Constant *ConstVal = cast<Constant>(Cond.first->getOperand(1));
170 if (Cond.second == ICmpInst::ICMP_EQ)
Florian Hahnc6c89bf2018-01-16 22:13:15 +0000171 setConstantInArgument(CS, Arg, ConstVal);
Florian Hahnbeda7d52017-12-13 03:05:20 +0000172 else if (ConstVal->getType()->isPointerTy() && ConstVal->isNullValue()) {
173 assert(Cond.second == ICmpInst::ICMP_NE);
Florian Hahnc6c89bf2018-01-16 22:13:15 +0000174 addNonNullAttribute(CS, Arg);
Jun Bum Lim0c990072017-11-03 20:41:16 +0000175 }
176 }
Florian Hahnbeda7d52017-12-13 03:05:20 +0000177}
178
179static SmallVector<BasicBlock *, 2> getTwoPredecessors(BasicBlock *BB) {
180 SmallVector<BasicBlock *, 2> Preds(predecessors((BB)));
181 assert(Preds.size() == 2 && "Expected exactly 2 predecessors!");
182 return Preds;
Jun Bum Lim0c990072017-11-03 20:41:16 +0000183}
184
Florian Hahnb4e3bad2018-02-14 13:59:12 +0000185static bool canSplitCallSite(CallSite CS, TargetTransformInfo &TTI) {
Matt Arsenaultf80c4242019-05-29 16:59:48 +0000186 if (CS.isConvergent() || CS.cannotDuplicate())
187 return false;
188
Jun Bum Lim0c990072017-11-03 20:41:16 +0000189 // FIXME: As of now we handle only CallInst. InvokeInst could be handled
190 // without too much effort.
191 Instruction *Instr = CS.getInstruction();
192 if (!isa<CallInst>(Instr))
193 return false;
194
Jun Bum Lim0c990072017-11-03 20:41:16 +0000195 BasicBlock *CallSiteBB = Instr->getParent();
Aditya Kumar373ce7e2018-07-21 14:13:44 +0000196 // Need 2 predecessors and cannot split an edge from an IndirectBrInst.
197 SmallVector<BasicBlock *, 2> Preds(predecessors(CallSiteBB));
198 if (Preds.size() != 2 || isa<IndirectBrInst>(Preds[0]->getTerminator()) ||
199 isa<IndirectBrInst>(Preds[1]->getTerminator()))
200 return false;
201
Sanjay Patelde58e932018-11-07 14:35:36 +0000202 // BasicBlock::canSplitPredecessors is more aggressive, so checking for
Aditya Kumar373ce7e2018-07-21 14:13:44 +0000203 // BasicBlock::isEHPad as well.
204 if (!CallSiteBB->canSplitPredecessors() || CallSiteBB->isEHPad())
205 return false;
206
Florian Hahnb4e3bad2018-02-14 13:59:12 +0000207 // Allow splitting a call-site only when the CodeSize cost of the
208 // instructions before the call is less then DuplicationThreshold. The
209 // instructions before the call will be duplicated in the split blocks and
210 // corresponding uses will be updated.
211 unsigned Cost = 0;
212 for (auto &InstBeforeCall :
213 llvm::make_range(CallSiteBB->begin(), Instr->getIterator())) {
214 Cost += TTI.getInstructionCost(&InstBeforeCall,
215 TargetTransformInfo::TCK_CodeSize);
216 if (Cost >= DuplicationThreshold)
217 return false;
218 }
Jun Bum Lim0c990072017-11-03 20:41:16 +0000219
Aditya Kumar373ce7e2018-07-21 14:13:44 +0000220 return true;
Jun Bum Lim0c990072017-11-03 20:41:16 +0000221}
222
Fedor Indutnyf9e09c12018-03-03 21:40:14 +0000223static Instruction *cloneInstForMustTail(Instruction *I, Instruction *Before,
224 Value *V) {
225 Instruction *Copy = I->clone();
226 Copy->setName(I->getName());
227 Copy->insertBefore(Before);
228 if (V)
229 Copy->setOperand(0, V);
230 return Copy;
231}
232
233/// Copy mandatory `musttail` return sequence that follows original `CI`, and
234/// link it up to `NewCI` value instead:
Florian Hahnc6c89bf2018-01-16 22:13:15 +0000235///
Fedor Indutnyf9e09c12018-03-03 21:40:14 +0000236/// * (optional) `bitcast NewCI to ...`
237/// * `ret bitcast or NewCI`
238///
239/// Insert this sequence right before `SplitBB`'s terminator, which will be
240/// cleaned up later in `splitCallSite` below.
241static void copyMustTailReturn(BasicBlock *SplitBB, Instruction *CI,
242 Instruction *NewCI) {
243 bool IsVoid = SplitBB->getParent()->getReturnType()->isVoidTy();
244 auto II = std::next(CI->getIterator());
245
246 BitCastInst* BCI = dyn_cast<BitCastInst>(&*II);
247 if (BCI)
248 ++II;
249
250 ReturnInst* RI = dyn_cast<ReturnInst>(&*II);
251 assert(RI && "`musttail` call must be followed by `ret` instruction");
252
Chandler Carruthedb12a82018-10-15 10:04:59 +0000253 Instruction *TI = SplitBB->getTerminator();
Fedor Indutnyf9e09c12018-03-03 21:40:14 +0000254 Value *V = NewCI;
255 if (BCI)
256 V = cloneInstForMustTail(BCI, TI, V);
257 cloneInstForMustTail(RI, TI, IsVoid ? nullptr : V);
258
259 // FIXME: remove TI here, `DuplicateInstructionsInSplitBetween` has a bug
260 // that prevents doing this now.
261}
262
Florian Hahnc6c89bf2018-01-16 22:13:15 +0000263/// For each (predecessor, conditions from predecessors) pair, it will split the
264/// basic block containing the call site, hook it up to the predecessor and
265/// replace the call instruction with new call instructions, which contain
266/// constraints based on the conditions from their predecessors.
Florian Hahn7e932892017-12-23 20:02:26 +0000267/// For example, in the IR below with an OR condition, the call-site can
Florian Hahnc6c89bf2018-01-16 22:13:15 +0000268/// be split. In this case, Preds for Tail is [(Header, a == null),
269/// (TBB, a != null, b == null)]. Tail is replaced by 2 split blocks, containing
270/// CallInst1, which has constraints based on the conditions from Head and
271/// CallInst2, which has constraints based on the conditions coming from TBB.
Jun Bum Lim0c990072017-11-03 20:41:16 +0000272///
Florian Hahn7e932892017-12-23 20:02:26 +0000273/// From :
Jun Bum Lim0c990072017-11-03 20:41:16 +0000274///
275/// Header:
276/// %c = icmp eq i32* %a, null
277/// br i1 %c %Tail, %TBB
278/// TBB:
279/// %c2 = icmp eq i32* %b, null
280/// br i1 %c %Tail, %End
281/// Tail:
282/// %ca = call i1 @callee (i32* %a, i32* %b)
283///
284/// to :
285///
286/// Header: // PredBB1 is Header
287/// %c = icmp eq i32* %a, null
288/// br i1 %c %Tail-split1, %TBB
289/// TBB: // PredBB2 is TBB
290/// %c2 = icmp eq i32* %b, null
291/// br i1 %c %Tail-split2, %End
292/// Tail-split1:
293/// %ca1 = call @callee (i32* null, i32* %b) // CallInst1
294/// br %Tail
295/// Tail-split2:
296/// %ca2 = call @callee (i32* nonnull %a, i32* null) // CallInst2
297/// br %Tail
298/// Tail:
299/// %p = phi i1 [%ca1, %Tail-split1],[%ca2, %Tail-split2]
300///
Florian Hahn7e932892017-12-23 20:02:26 +0000301/// Note that in case any arguments at the call-site are constrained by its
302/// predecessors, new call-sites with more constrained arguments will be
303/// created in createCallSitesOnPredicatedArgument().
Florian Hahnc6c89bf2018-01-16 22:13:15 +0000304static void splitCallSite(
305 CallSite CS,
Florian Hahn9bc0bc42018-03-22 15:23:33 +0000306 const SmallVectorImpl<std::pair<BasicBlock *, ConditionsTy>> &Preds,
Florian Hahn107d0a82018-11-13 17:54:43 +0000307 DomTreeUpdater &DTU) {
Jun Bum Lim0c990072017-11-03 20:41:16 +0000308 Instruction *Instr = CS.getInstruction();
309 BasicBlock *TailBB = Instr->getParent();
Fedor Indutnyf9e09c12018-03-03 21:40:14 +0000310 bool IsMustTailCall = CS.isMustTailCall();
Jun Bum Lim0c990072017-11-03 20:41:16 +0000311
Florian Hahnc6c89bf2018-01-16 22:13:15 +0000312 PHINode *CallPN = nullptr;
Fedor Indutnyf9e09c12018-03-03 21:40:14 +0000313
314 // `musttail` calls must be followed by optional `bitcast`, and `ret`. The
315 // split blocks will be terminated right after that so there're no users for
316 // this phi in a `TailBB`.
Florian Hahn5b7e21a2018-09-11 17:55:58 +0000317 if (!IsMustTailCall && !Instr->use_empty()) {
Florian Hahnc6c89bf2018-01-16 22:13:15 +0000318 CallPN = PHINode::Create(Instr->getType(), Preds.size(), "phi.call");
Florian Hahn5b7e21a2018-09-11 17:55:58 +0000319 CallPN->setDebugLoc(Instr->getDebugLoc());
320 }
Jun Bum Lim0c990072017-11-03 20:41:16 +0000321
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000322 LLVM_DEBUG(dbgs() << "split call-site : " << *Instr << " into \n");
Florian Hahnb4e3bad2018-02-14 13:59:12 +0000323
324 assert(Preds.size() == 2 && "The ValueToValueMaps array has size 2.");
325 // ValueToValueMapTy is neither copy nor moveable, so we use a simple array
326 // here.
327 ValueToValueMapTy ValueToValueMaps[2];
328 for (unsigned i = 0; i < Preds.size(); i++) {
329 BasicBlock *PredBB = Preds[i].first;
330 BasicBlock *SplitBlock = DuplicateInstructionsInSplitBetween(
Florian Hahn9bc0bc42018-03-22 15:23:33 +0000331 TailBB, PredBB, &*std::next(Instr->getIterator()), ValueToValueMaps[i],
Florian Hahn107d0a82018-11-13 17:54:43 +0000332 DTU);
Florian Hahnc6c89bf2018-01-16 22:13:15 +0000333 assert(SplitBlock && "Unexpected new basic block split.");
Jun Bum Lim0c990072017-11-03 20:41:16 +0000334
Florian Hahnb4e3bad2018-02-14 13:59:12 +0000335 Instruction *NewCI =
336 &*std::prev(SplitBlock->getTerminator()->getIterator());
Florian Hahnc6c89bf2018-01-16 22:13:15 +0000337 CallSite NewCS(NewCI);
Florian Hahnb4e3bad2018-02-14 13:59:12 +0000338 addConditions(NewCS, Preds[i].second);
Jun Bum Lim0c990072017-11-03 20:41:16 +0000339
Florian Hahnc6c89bf2018-01-16 22:13:15 +0000340 // Handle PHIs used as arguments in the call-site.
341 for (PHINode &PN : TailBB->phis()) {
342 unsigned ArgNo = 0;
343 for (auto &CI : CS.args()) {
344 if (&*CI == &PN) {
345 NewCS.setArgument(ArgNo, PN.getIncomingValueForBlock(SplitBlock));
346 }
347 ++ArgNo;
Jun Bum Lim0c990072017-11-03 20:41:16 +0000348 }
Jun Bum Lim0c990072017-11-03 20:41:16 +0000349 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000350 LLVM_DEBUG(dbgs() << " " << *NewCI << " in " << SplitBlock->getName()
351 << "\n");
Florian Hahnc6c89bf2018-01-16 22:13:15 +0000352 if (CallPN)
353 CallPN->addIncoming(NewCI, SplitBlock);
Fedor Indutnyf9e09c12018-03-03 21:40:14 +0000354
355 // Clone and place bitcast and return instructions before `TI`
356 if (IsMustTailCall)
357 copyMustTailReturn(SplitBlock, Instr, NewCI);
358 }
359
360 NumCallSiteSplit++;
361
362 // FIXME: remove TI in `copyMustTailReturn`
363 if (IsMustTailCall) {
364 // Remove superfluous `br` terminators from the end of the Split blocks
Fedor Indutny364b9c22018-03-03 22:34:38 +0000365 // NOTE: Removing terminator removes the SplitBlock from the TailBB's
366 // predecessors. Therefore we must get complete list of Splits before
367 // attempting removal.
368 SmallVector<BasicBlock *, 2> Splits(predecessors((TailBB)));
369 assert(Splits.size() == 2 && "Expected exactly 2 splits!");
Joseph Tremoulet926ee452018-11-29 15:27:04 +0000370 for (unsigned i = 0; i < Splits.size(); i++) {
Fedor Indutny364b9c22018-03-03 22:34:38 +0000371 Splits[i]->getTerminator()->eraseFromParent();
Chijun Sima70e97162019-02-22 13:48:38 +0000372 DTU.applyUpdatesPermissive({{DominatorTree::Delete, Splits[i], TailBB}});
Joseph Tremoulet926ee452018-11-29 15:27:04 +0000373 }
Fedor Indutnyf9e09c12018-03-03 21:40:14 +0000374
375 // Erase the tail block once done with musttail patching
Florian Hahn107d0a82018-11-13 17:54:43 +0000376 DTU.deleteBB(TailBB);
Fedor Indutnyf9e09c12018-03-03 21:40:14 +0000377 return;
Jun Bum Lim0c990072017-11-03 20:41:16 +0000378 }
379
Florian Hahnb4e3bad2018-02-14 13:59:12 +0000380 auto *OriginalBegin = &*TailBB->begin();
Jun Bum Lim0c990072017-11-03 20:41:16 +0000381 // Replace users of the original call with a PHI mering call-sites split.
Florian Hahnc6c89bf2018-01-16 22:13:15 +0000382 if (CallPN) {
Florian Hahnb4e3bad2018-02-14 13:59:12 +0000383 CallPN->insertBefore(OriginalBegin);
Florian Hahnc6c89bf2018-01-16 22:13:15 +0000384 Instr->replaceAllUsesWith(CallPN);
Jun Bum Lim0c990072017-11-03 20:41:16 +0000385 }
Florian Hahnc6c89bf2018-01-16 22:13:15 +0000386
Florian Hahnb4e3bad2018-02-14 13:59:12 +0000387 // Remove instructions moved to split blocks from TailBB, from the duplicated
388 // call instruction to the beginning of the basic block. If an instruction
389 // has any uses, add a new PHI node to combine the values coming from the
390 // split blocks. The new PHI nodes are placed before the first original
391 // instruction, so we do not end up deleting them. By using reverse-order, we
392 // do not introduce unnecessary PHI nodes for def-use chains from the call
393 // instruction to the beginning of the block.
394 auto I = Instr->getReverseIterator();
395 while (I != TailBB->rend()) {
396 Instruction *CurrentI = &*I++;
397 if (!CurrentI->use_empty()) {
398 // If an existing PHI has users after the call, there is no need to create
399 // a new one.
400 if (isa<PHINode>(CurrentI))
401 continue;
402 PHINode *NewPN = PHINode::Create(CurrentI->getType(), Preds.size());
Florian Hahn5b7e21a2018-09-11 17:55:58 +0000403 NewPN->setDebugLoc(CurrentI->getDebugLoc());
Florian Hahnb4e3bad2018-02-14 13:59:12 +0000404 for (auto &Mapping : ValueToValueMaps)
405 NewPN->addIncoming(Mapping[CurrentI],
406 cast<Instruction>(Mapping[CurrentI])->getParent());
407 NewPN->insertBefore(&*TailBB->begin());
408 CurrentI->replaceAllUsesWith(NewPN);
409 }
410 CurrentI->eraseFromParent();
411 // We are done once we handled the first original instruction in TailBB.
412 if (CurrentI == OriginalBegin)
413 break;
414 }
Jun Bum Lim0c990072017-11-03 20:41:16 +0000415}
416
Jun Bum Lim0c990072017-11-03 20:41:16 +0000417// Return true if the call-site has an argument which is a PHI with only
418// constant incoming values.
419static bool isPredicatedOnPHI(CallSite CS) {
420 Instruction *Instr = CS.getInstruction();
421 BasicBlock *Parent = Instr->getParent();
Mikael Holmen66cf3832017-12-12 07:29:57 +0000422 if (Instr != Parent->getFirstNonPHIOrDbg())
Jun Bum Lim0c990072017-11-03 20:41:16 +0000423 return false;
424
425 for (auto &BI : *Parent) {
426 if (PHINode *PN = dyn_cast<PHINode>(&BI)) {
427 for (auto &I : CS.args())
428 if (&*I == PN) {
429 assert(PN->getNumIncomingValues() == 2 &&
430 "Unexpected number of incoming values");
431 if (PN->getIncomingBlock(0) == PN->getIncomingBlock(1))
432 return false;
433 if (PN->getIncomingValue(0) == PN->getIncomingValue(1))
434 continue;
435 if (isa<Constant>(PN->getIncomingValue(0)) &&
436 isa<Constant>(PN->getIncomingValue(1)))
437 return true;
438 }
439 }
440 break;
441 }
442 return false;
443}
444
Florian Hahn107d0a82018-11-13 17:54:43 +0000445using PredsWithCondsTy = SmallVector<std::pair<BasicBlock *, ConditionsTy>, 2>;
446
447// Check if any of the arguments in CS are predicated on a PHI node and return
448// the set of predecessors we should use for splitting.
449static PredsWithCondsTy shouldSplitOnPHIPredicatedArgument(CallSite CS) {
Florian Hahn2a266a32017-11-18 18:14:13 +0000450 if (!isPredicatedOnPHI(CS))
Florian Hahn107d0a82018-11-13 17:54:43 +0000451 return {};
Jun Bum Lim0c990072017-11-03 20:41:16 +0000452
Florian Hahn2a266a32017-11-18 18:14:13 +0000453 auto Preds = getTwoPredecessors(CS.getInstruction()->getParent());
Florian Hahn107d0a82018-11-13 17:54:43 +0000454 return {{Preds[0], {}}, {Preds[1], {}}};
Florian Hahn2a266a32017-11-18 18:14:13 +0000455}
Jun Bum Lim0c990072017-11-03 20:41:16 +0000456
Florian Hahn107d0a82018-11-13 17:54:43 +0000457// Checks if any of the arguments in CS are predicated in a predecessor and
458// returns a list of predecessors with the conditions that hold on their edges
459// to CS.
Florian Hahn505091a2018-11-14 10:04:30 +0000460static PredsWithCondsTy shouldSplitOnPredicatedArgument(CallSite CS,
461 DomTreeUpdater &DTU) {
Florian Hahn2a266a32017-11-18 18:14:13 +0000462 auto Preds = getTwoPredecessors(CS.getInstruction()->getParent());
Florian Hahn7e932892017-12-23 20:02:26 +0000463 if (Preds[0] == Preds[1])
Florian Hahn107d0a82018-11-13 17:54:43 +0000464 return {};
Florian Hahn2a266a32017-11-18 18:14:13 +0000465
Florian Hahn505091a2018-11-14 10:04:30 +0000466 // We can stop recording conditions once we reached the immediate dominator
467 // for the block containing the call site. Conditions in predecessors of the
468 // that node will be the same for all paths to the call site and splitting
469 // is not beneficial.
470 assert(DTU.hasDomTree() && "We need a DTU with a valid DT!");
471 auto *CSDTNode = DTU.getDomTree().getNode(CS.getInstruction()->getParent());
472 BasicBlock *StopAt = CSDTNode ? CSDTNode->getIDom()->getBlock() : nullptr;
473
Florian Hahnc6c89bf2018-01-16 22:13:15 +0000474 SmallVector<std::pair<BasicBlock *, ConditionsTy>, 2> PredsCS;
475 for (auto *Pred : make_range(Preds.rbegin(), Preds.rend())) {
476 ConditionsTy Conditions;
Florian Hahn505091a2018-11-14 10:04:30 +0000477 // Record condition on edge BB(CS) <- Pred
478 recordCondition(CS, Pred, CS.getInstruction()->getParent(), Conditions);
479 // Record conditions following Pred's single predecessors.
480 recordConditions(CS, Pred, Conditions, StopAt);
Florian Hahnc6c89bf2018-01-16 22:13:15 +0000481 PredsCS.push_back({Pred, Conditions});
482 }
Florian Hahn2a266a32017-11-18 18:14:13 +0000483
Fangrui Song2e83b2e2018-10-19 06:12:02 +0000484 if (all_of(PredsCS, [](const std::pair<BasicBlock *, ConditionsTy> &P) {
485 return P.second.empty();
486 }))
Florian Hahn107d0a82018-11-13 17:54:43 +0000487 return {};
Florian Hahnbeda7d52017-12-13 03:05:20 +0000488
Florian Hahn107d0a82018-11-13 17:54:43 +0000489 return PredsCS;
Jun Bum Lim0c990072017-11-03 20:41:16 +0000490}
491
Florian Hahn9bc0bc42018-03-22 15:23:33 +0000492static bool tryToSplitCallSite(CallSite CS, TargetTransformInfo &TTI,
Florian Hahn107d0a82018-11-13 17:54:43 +0000493 DomTreeUpdater &DTU) {
494 // Check if we can split the call site.
Florian Hahnb4e3bad2018-02-14 13:59:12 +0000495 if (!CS.arg_size() || !canSplitCallSite(CS, TTI))
Jun Bum Lim0c990072017-11-03 20:41:16 +0000496 return false;
Florian Hahn107d0a82018-11-13 17:54:43 +0000497
Florian Hahn505091a2018-11-14 10:04:30 +0000498 auto PredsWithConds = shouldSplitOnPredicatedArgument(CS, DTU);
Florian Hahn107d0a82018-11-13 17:54:43 +0000499 if (PredsWithConds.empty())
500 PredsWithConds = shouldSplitOnPHIPredicatedArgument(CS);
501 if (PredsWithConds.empty())
502 return false;
503
504 splitCallSite(CS, PredsWithConds, DTU);
505 return true;
Jun Bum Lim0c990072017-11-03 20:41:16 +0000506}
507
Florian Hahnb4e3bad2018-02-14 13:59:12 +0000508static bool doCallSiteSplitting(Function &F, TargetLibraryInfo &TLI,
Florian Hahn505091a2018-11-14 10:04:30 +0000509 TargetTransformInfo &TTI, DominatorTree &DT) {
Florian Hahn107d0a82018-11-13 17:54:43 +0000510
Florian Hahn505091a2018-11-14 10:04:30 +0000511 DomTreeUpdater DTU(&DT, DomTreeUpdater::UpdateStrategy::Lazy);
Jun Bum Lim0c990072017-11-03 20:41:16 +0000512 bool Changed = false;
513 for (Function::iterator BI = F.begin(), BE = F.end(); BI != BE;) {
514 BasicBlock &BB = *BI++;
Florian Hahn517dc512018-03-06 14:00:58 +0000515 auto II = BB.getFirstNonPHIOrDbg()->getIterator();
516 auto IE = BB.getTerminator()->getIterator();
517 // Iterate until we reach the terminator instruction. tryToSplitCallSite
518 // can replace BB's terminator in case BB is a successor of itself. In that
519 // case, IE will be invalidated and we also have to check the current
520 // terminator.
521 while (II != IE && &*II != BB.getTerminator()) {
Jun Bum Lim0c990072017-11-03 20:41:16 +0000522 Instruction *I = &*II++;
523 CallSite CS(cast<Value>(I));
524 if (!CS || isa<IntrinsicInst>(I) || isInstructionTriviallyDead(I, &TLI))
525 continue;
526
527 Function *Callee = CS.getCalledFunction();
528 if (!Callee || Callee->isDeclaration())
529 continue;
Fedor Indutnyf9e09c12018-03-03 21:40:14 +0000530
531 // Successful musttail call-site splits result in erased CI and erased BB.
532 // Check if such path is possible before attempting the splitting.
533 bool IsMustTail = CS.isMustTailCall();
534
Florian Hahn107d0a82018-11-13 17:54:43 +0000535 Changed |= tryToSplitCallSite(CS, TTI, DTU);
Fedor Indutnyf9e09c12018-03-03 21:40:14 +0000536
537 // There're no interesting instructions after this. The call site
538 // itself might have been erased on splitting.
539 if (IsMustTail)
540 break;
Jun Bum Lim0c990072017-11-03 20:41:16 +0000541 }
542 }
543 return Changed;
544}
545
546namespace {
547struct CallSiteSplittingLegacyPass : public FunctionPass {
548 static char ID;
549 CallSiteSplittingLegacyPass() : FunctionPass(ID) {
550 initializeCallSiteSplittingLegacyPassPass(*PassRegistry::getPassRegistry());
551 }
552
553 void getAnalysisUsage(AnalysisUsage &AU) const override {
554 AU.addRequired<TargetLibraryInfoWrapperPass>();
Florian Hahnb4e3bad2018-02-14 13:59:12 +0000555 AU.addRequired<TargetTransformInfoWrapperPass>();
Florian Hahn505091a2018-11-14 10:04:30 +0000556 AU.addRequired<DominatorTreeWrapperPass>();
Florian Hahn9bc0bc42018-03-22 15:23:33 +0000557 AU.addPreserved<DominatorTreeWrapperPass>();
Jun Bum Lim0c990072017-11-03 20:41:16 +0000558 FunctionPass::getAnalysisUsage(AU);
559 }
560
561 bool runOnFunction(Function &F) override {
562 if (skipFunction(F))
563 return false;
564
565 auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Florian Hahnb4e3bad2018-02-14 13:59:12 +0000566 auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
Florian Hahn505091a2018-11-14 10:04:30 +0000567 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
568 return doCallSiteSplitting(F, TLI, TTI, DT);
Jun Bum Lim0c990072017-11-03 20:41:16 +0000569 }
570};
571} // namespace
572
573char CallSiteSplittingLegacyPass::ID = 0;
574INITIALIZE_PASS_BEGIN(CallSiteSplittingLegacyPass, "callsite-splitting",
575 "Call-site splitting", false, false)
576INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Florian Hahnb4e3bad2018-02-14 13:59:12 +0000577INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
Florian Hahn505091a2018-11-14 10:04:30 +0000578INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Jun Bum Lim0c990072017-11-03 20:41:16 +0000579INITIALIZE_PASS_END(CallSiteSplittingLegacyPass, "callsite-splitting",
580 "Call-site splitting", false, false)
581FunctionPass *llvm::createCallSiteSplittingPass() {
582 return new CallSiteSplittingLegacyPass();
583}
584
585PreservedAnalyses CallSiteSplittingPass::run(Function &F,
586 FunctionAnalysisManager &AM) {
587 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
Florian Hahnb4e3bad2018-02-14 13:59:12 +0000588 auto &TTI = AM.getResult<TargetIRAnalysis>(F);
Florian Hahn505091a2018-11-14 10:04:30 +0000589 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
Jun Bum Lim0c990072017-11-03 20:41:16 +0000590
Florian Hahn9bc0bc42018-03-22 15:23:33 +0000591 if (!doCallSiteSplitting(F, TLI, TTI, DT))
Jun Bum Lim0c990072017-11-03 20:41:16 +0000592 return PreservedAnalyses::all();
593 PreservedAnalyses PA;
Florian Hahn9bc0bc42018-03-22 15:23:33 +0000594 PA.preserve<DominatorTreeAnalysis>();
Jun Bum Lim0c990072017-11-03 20:41:16 +0000595 return PA;
596}