1 //===- CallSiteSplitting.cpp ----------------------------------------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
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 :
15 // 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.
26 // callee(null) // set the known constant value
28 // callee(nonnull ptr) // set non-null attribute in the argument
30 // 2) We can also split a call-site based on constant incoming values of a PHI
34 // %c = icmp eq i32 %i1, %i2
35 // br i1 %c, label %Tail, label %TBB
39 // %p = phi i32 [ 0, %Header], [ 1, %TBB]
40 // call void @bar(i32 %p)
43 // %c = icmp eq i32 %i1, %i2
44 // br i1 %c, label %Tail-split0, label %TBB
46 // br label %Tail-split1
48 // call void @bar(i32 0)
51 // call void @bar(i32 1)
54 // %p = phi i32 [ 0, %Tail-split0 ], [ 1, %Tail-split1 ]
56 //===----------------------------------------------------------------------===//
58 #include "llvm/Transforms/Scalar/CallSiteSplitting.h"
59 #include "llvm/ADT/Statistic.h"
60 #include "llvm/Analysis/TargetLibraryInfo.h"
61 #include "llvm/Analysis/TargetTransformInfo.h"
62 #include "llvm/IR/IntrinsicInst.h"
63 #include "llvm/IR/PatternMatch.h"
64 #include "llvm/InitializePasses.h"
65 #include "llvm/Support/CommandLine.h"
66 #include "llvm/Support/Debug.h"
67 #include "llvm/Transforms/Scalar.h"
68 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
69 #include "llvm/Transforms/Utils/Cloning.h"
70 #include "llvm/Transforms/Utils/Local.h"
73 using namespace PatternMatch
;
75 #define DEBUG_TYPE "callsite-splitting"
77 STATISTIC(NumCallSiteSplit
, "Number of call-site split");
79 /// Only allow instructions before a call, if their CodeSize cost is below
80 /// DuplicationThreshold. Those instructions need to be duplicated in all
82 static cl::opt
<unsigned>
83 DuplicationThreshold("callsite-splitting-duplication-threshold", cl::Hidden
,
84 cl::desc("Only allow instructions before a call, if "
85 "their cost is below DuplicationThreshold"),
88 static void addNonNullAttribute(CallBase
&CB
, Value
*Op
) {
90 for (auto &I
: CB
.args()) {
92 CB
.addParamAttr(ArgNo
, Attribute::NonNull
);
97 static void setConstantInArgument(CallBase
&CB
, Value
*Op
,
98 Constant
*ConstValue
) {
100 for (auto &I
: CB
.args()) {
102 // It is possible we have already added the non-null attribute to the
103 // parameter by using an earlier constraining condition.
104 CB
.removeParamAttr(ArgNo
, Attribute::NonNull
);
105 CB
.setArgOperand(ArgNo
, ConstValue
);
111 static bool isCondRelevantToAnyCallArgument(ICmpInst
*Cmp
, CallBase
&CB
) {
112 assert(isa
<Constant
>(Cmp
->getOperand(1)) && "Expected a constant operand.");
113 Value
*Op0
= Cmp
->getOperand(0);
115 for (auto I
= CB
.arg_begin(), E
= CB
.arg_end(); I
!= E
; ++I
, ++ArgNo
) {
116 // Don't consider constant or arguments that are already known non-null.
117 if (isa
<Constant
>(*I
) || CB
.paramHasAttr(ArgNo
, Attribute::NonNull
))
126 typedef std::pair
<ICmpInst
*, unsigned> ConditionTy
;
127 typedef SmallVector
<ConditionTy
, 2> ConditionsTy
;
129 /// If From has a conditional jump to To, add the condition to Conditions,
130 /// if it is relevant to any argument at CB.
131 static void recordCondition(CallBase
&CB
, BasicBlock
*From
, BasicBlock
*To
,
132 ConditionsTy
&Conditions
) {
133 auto *BI
= dyn_cast
<BranchInst
>(From
->getTerminator());
134 if (!BI
|| !BI
->isConditional())
137 CmpInst::Predicate Pred
;
138 Value
*Cond
= BI
->getCondition();
139 if (!match(Cond
, m_ICmp(Pred
, m_Value(), m_Constant())))
142 ICmpInst
*Cmp
= cast
<ICmpInst
>(Cond
);
143 if (Pred
== ICmpInst::ICMP_EQ
|| Pred
== ICmpInst::ICMP_NE
)
144 if (isCondRelevantToAnyCallArgument(Cmp
, CB
))
145 Conditions
.push_back({Cmp
, From
->getTerminator()->getSuccessor(0) == To
147 : Cmp
->getInversePredicate()});
150 /// Record ICmp conditions relevant to any argument in CB following Pred's
151 /// single predecessors. If there are conflicting conditions along a path, like
152 /// x == 1 and x == 0, the first condition will be used. We stop once we reach
153 /// an edge to StopAt.
154 static void recordConditions(CallBase
&CB
, BasicBlock
*Pred
,
155 ConditionsTy
&Conditions
, BasicBlock
*StopAt
) {
156 BasicBlock
*From
= Pred
;
157 BasicBlock
*To
= Pred
;
158 SmallPtrSet
<BasicBlock
*, 4> Visited
;
159 while (To
!= StopAt
&& !Visited
.count(From
->getSinglePredecessor()) &&
160 (From
= From
->getSinglePredecessor())) {
161 recordCondition(CB
, From
, To
, Conditions
);
162 Visited
.insert(From
);
167 static void addConditions(CallBase
&CB
, const ConditionsTy
&Conditions
) {
168 for (auto &Cond
: Conditions
) {
169 Value
*Arg
= Cond
.first
->getOperand(0);
170 Constant
*ConstVal
= cast
<Constant
>(Cond
.first
->getOperand(1));
171 if (Cond
.second
== ICmpInst::ICMP_EQ
)
172 setConstantInArgument(CB
, Arg
, ConstVal
);
173 else if (ConstVal
->getType()->isPointerTy() && ConstVal
->isNullValue()) {
174 assert(Cond
.second
== ICmpInst::ICMP_NE
);
175 addNonNullAttribute(CB
, Arg
);
180 static SmallVector
<BasicBlock
*, 2> getTwoPredecessors(BasicBlock
*BB
) {
181 SmallVector
<BasicBlock
*, 2> Preds(predecessors((BB
)));
182 assert(Preds
.size() == 2 && "Expected exactly 2 predecessors!");
186 static bool canSplitCallSite(CallBase
&CB
, TargetTransformInfo
&TTI
) {
187 if (CB
.isConvergent() || CB
.cannotDuplicate())
190 // FIXME: As of now we handle only CallInst. InvokeInst could be handled
191 // without too much effort.
192 if (!isa
<CallInst
>(CB
))
195 BasicBlock
*CallSiteBB
= CB
.getParent();
196 // 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()))
202 // BasicBlock::canSplitPredecessors is more aggressive, so checking for
203 // BasicBlock::isEHPad as well.
204 if (!CallSiteBB
->canSplitPredecessors() || CallSiteBB
->isEHPad())
207 // 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 InstructionCost Cost
= 0;
212 for (auto &InstBeforeCall
:
213 llvm::make_range(CallSiteBB
->begin(), CB
.getIterator())) {
214 Cost
+= TTI
.getInstructionCost(&InstBeforeCall
,
215 TargetTransformInfo::TCK_CodeSize
);
216 if (Cost
>= DuplicationThreshold
)
223 static Instruction
*cloneInstForMustTail(Instruction
*I
, Instruction
*Before
,
225 Instruction
*Copy
= I
->clone();
226 Copy
->setName(I
->getName());
227 Copy
->insertBefore(Before
);
229 Copy
->setOperand(0, V
);
233 /// Copy mandatory `musttail` return sequence that follows original `CI`, and
234 /// link it up to `NewCI` value instead:
236 /// * (optional) `bitcast NewCI to ...`
237 /// * `ret bitcast or NewCI`
239 /// Insert this sequence right before `SplitBB`'s terminator, which will be
240 /// cleaned up later in `splitCallSite` below.
241 static void copyMustTailReturn(BasicBlock
*SplitBB
, Instruction
*CI
,
242 Instruction
*NewCI
) {
243 bool IsVoid
= SplitBB
->getParent()->getReturnType()->isVoidTy();
244 auto II
= std::next(CI
->getIterator());
246 BitCastInst
* BCI
= dyn_cast
<BitCastInst
>(&*II
);
250 ReturnInst
* RI
= dyn_cast
<ReturnInst
>(&*II
);
251 assert(RI
&& "`musttail` call must be followed by `ret` instruction");
253 Instruction
*TI
= SplitBB
->getTerminator();
256 V
= cloneInstForMustTail(BCI
, TI
, V
);
257 cloneInstForMustTail(RI
, TI
, IsVoid
? nullptr : V
);
259 // FIXME: remove TI here, `DuplicateInstructionsInSplitBetween` has a bug
260 // that prevents doing this now.
263 /// 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.
267 /// For example, in the IR below with an OR condition, the call-site can
268 /// 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.
276 /// %c = icmp eq i32* %a, null
277 /// br i1 %c %Tail, %TBB
279 /// %c2 = icmp eq i32* %b, null
280 /// br i1 %c %Tail, %End
282 /// %ca = call i1 @callee (i32* %a, i32* %b)
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
293 /// %ca1 = call @callee (i32* null, i32* %b) // CallInst1
296 /// %ca2 = call @callee (i32* nonnull %a, i32* null) // CallInst2
299 /// %p = phi i1 [%ca1, %Tail-split1],[%ca2, %Tail-split2]
301 /// 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().
304 static void splitCallSite(
306 const SmallVectorImpl
<std::pair
<BasicBlock
*, ConditionsTy
>> &Preds
,
307 DomTreeUpdater
&DTU
) {
308 BasicBlock
*TailBB
= CB
.getParent();
309 bool IsMustTailCall
= CB
.isMustTailCall();
311 PHINode
*CallPN
= nullptr;
313 // `musttail` calls must be followed by optional `bitcast`, and `ret`. The
314 // split blocks will be terminated right after that so there're no users for
315 // this phi in a `TailBB`.
316 if (!IsMustTailCall
&& !CB
.use_empty()) {
317 CallPN
= PHINode::Create(CB
.getType(), Preds
.size(), "phi.call");
318 CallPN
->setDebugLoc(CB
.getDebugLoc());
321 LLVM_DEBUG(dbgs() << "split call-site : " << CB
<< " into \n");
323 assert(Preds
.size() == 2 && "The ValueToValueMaps array has size 2.");
324 // ValueToValueMapTy is neither copy nor moveable, so we use a simple array
326 ValueToValueMapTy ValueToValueMaps
[2];
327 for (unsigned i
= 0; i
< Preds
.size(); i
++) {
328 BasicBlock
*PredBB
= Preds
[i
].first
;
329 BasicBlock
*SplitBlock
= DuplicateInstructionsInSplitBetween(
330 TailBB
, PredBB
, &*std::next(CB
.getIterator()), ValueToValueMaps
[i
],
332 assert(SplitBlock
&& "Unexpected new basic block split.");
335 cast
<CallBase
>(&*std::prev(SplitBlock
->getTerminator()->getIterator()));
336 addConditions(*NewCI
, Preds
[i
].second
);
338 // Handle PHIs used as arguments in the call-site.
339 for (PHINode
&PN
: TailBB
->phis()) {
341 for (auto &CI
: CB
.args()) {
343 NewCI
->setArgOperand(ArgNo
, PN
.getIncomingValueForBlock(SplitBlock
));
348 LLVM_DEBUG(dbgs() << " " << *NewCI
<< " in " << SplitBlock
->getName()
351 CallPN
->addIncoming(NewCI
, SplitBlock
);
353 // Clone and place bitcast and return instructions before `TI`
355 copyMustTailReturn(SplitBlock
, &CB
, NewCI
);
360 // FIXME: remove TI in `copyMustTailReturn`
361 if (IsMustTailCall
) {
362 // Remove superfluous `br` terminators from the end of the Split blocks
363 // NOTE: Removing terminator removes the SplitBlock from the TailBB's
364 // predecessors. Therefore we must get complete list of Splits before
365 // attempting removal.
366 SmallVector
<BasicBlock
*, 2> Splits(predecessors((TailBB
)));
367 assert(Splits
.size() == 2 && "Expected exactly 2 splits!");
368 for (unsigned i
= 0; i
< Splits
.size(); i
++) {
369 Splits
[i
]->getTerminator()->eraseFromParent();
370 DTU
.applyUpdatesPermissive({{DominatorTree::Delete
, Splits
[i
], TailBB
}});
373 // Erase the tail block once done with musttail patching
374 DTU
.deleteBB(TailBB
);
378 auto *OriginalBegin
= &*TailBB
->begin();
379 // Replace users of the original call with a PHI mering call-sites split.
381 CallPN
->insertBefore(OriginalBegin
);
382 CB
.replaceAllUsesWith(CallPN
);
385 // Remove instructions moved to split blocks from TailBB, from the duplicated
386 // call instruction to the beginning of the basic block. If an instruction
387 // has any uses, add a new PHI node to combine the values coming from the
388 // split blocks. The new PHI nodes are placed before the first original
389 // instruction, so we do not end up deleting them. By using reverse-order, we
390 // do not introduce unnecessary PHI nodes for def-use chains from the call
391 // instruction to the beginning of the block.
392 auto I
= CB
.getReverseIterator();
393 while (I
!= TailBB
->rend()) {
394 Instruction
*CurrentI
= &*I
++;
395 if (!CurrentI
->use_empty()) {
396 // If an existing PHI has users after the call, there is no need to create
398 if (isa
<PHINode
>(CurrentI
))
400 PHINode
*NewPN
= PHINode::Create(CurrentI
->getType(), Preds
.size());
401 NewPN
->setDebugLoc(CurrentI
->getDebugLoc());
402 for (auto &Mapping
: ValueToValueMaps
)
403 NewPN
->addIncoming(Mapping
[CurrentI
],
404 cast
<Instruction
>(Mapping
[CurrentI
])->getParent());
405 NewPN
->insertBefore(&*TailBB
->begin());
406 CurrentI
->replaceAllUsesWith(NewPN
);
408 CurrentI
->eraseFromParent();
409 // We are done once we handled the first original instruction in TailBB.
410 if (CurrentI
== OriginalBegin
)
415 // Return true if the call-site has an argument which is a PHI with only
416 // constant incoming values.
417 static bool isPredicatedOnPHI(CallBase
&CB
) {
418 BasicBlock
*Parent
= CB
.getParent();
419 if (&CB
!= Parent
->getFirstNonPHIOrDbg())
422 for (auto &PN
: Parent
->phis()) {
423 for (auto &Arg
: CB
.args()) {
426 assert(PN
.getNumIncomingValues() == 2 &&
427 "Unexpected number of incoming values");
428 if (PN
.getIncomingBlock(0) == PN
.getIncomingBlock(1))
430 if (PN
.getIncomingValue(0) == PN
.getIncomingValue(1))
432 if (isa
<Constant
>(PN
.getIncomingValue(0)) &&
433 isa
<Constant
>(PN
.getIncomingValue(1)))
440 using PredsWithCondsTy
= SmallVector
<std::pair
<BasicBlock
*, ConditionsTy
>, 2>;
442 // Check if any of the arguments in CS are predicated on a PHI node and return
443 // the set of predecessors we should use for splitting.
444 static PredsWithCondsTy
shouldSplitOnPHIPredicatedArgument(CallBase
&CB
) {
445 if (!isPredicatedOnPHI(CB
))
448 auto Preds
= getTwoPredecessors(CB
.getParent());
449 return {{Preds
[0], {}}, {Preds
[1], {}}};
452 // Checks if any of the arguments in CS are predicated in a predecessor and
453 // returns a list of predecessors with the conditions that hold on their edges
455 static PredsWithCondsTy
shouldSplitOnPredicatedArgument(CallBase
&CB
,
456 DomTreeUpdater
&DTU
) {
457 auto Preds
= getTwoPredecessors(CB
.getParent());
458 if (Preds
[0] == Preds
[1])
461 // We can stop recording conditions once we reached the immediate dominator
462 // for the block containing the call site. Conditions in predecessors of the
463 // that node will be the same for all paths to the call site and splitting
464 // is not beneficial.
465 assert(DTU
.hasDomTree() && "We need a DTU with a valid DT!");
466 auto *CSDTNode
= DTU
.getDomTree().getNode(CB
.getParent());
467 BasicBlock
*StopAt
= CSDTNode
? CSDTNode
->getIDom()->getBlock() : nullptr;
469 SmallVector
<std::pair
<BasicBlock
*, ConditionsTy
>, 2> PredsCS
;
470 for (auto *Pred
: make_range(Preds
.rbegin(), Preds
.rend())) {
471 ConditionsTy Conditions
;
472 // Record condition on edge BB(CS) <- Pred
473 recordCondition(CB
, Pred
, CB
.getParent(), Conditions
);
474 // Record conditions following Pred's single predecessors.
475 recordConditions(CB
, Pred
, Conditions
, StopAt
);
476 PredsCS
.push_back({Pred
, Conditions
});
479 if (all_of(PredsCS
, [](const std::pair
<BasicBlock
*, ConditionsTy
> &P
) {
480 return P
.second
.empty();
487 static bool tryToSplitCallSite(CallBase
&CB
, TargetTransformInfo
&TTI
,
488 DomTreeUpdater
&DTU
) {
489 // Check if we can split the call site.
490 if (!CB
.arg_size() || !canSplitCallSite(CB
, TTI
))
493 auto PredsWithConds
= shouldSplitOnPredicatedArgument(CB
, DTU
);
494 if (PredsWithConds
.empty())
495 PredsWithConds
= shouldSplitOnPHIPredicatedArgument(CB
);
496 if (PredsWithConds
.empty())
499 splitCallSite(CB
, PredsWithConds
, DTU
);
503 static bool doCallSiteSplitting(Function
&F
, TargetLibraryInfo
&TLI
,
504 TargetTransformInfo
&TTI
, DominatorTree
&DT
) {
506 DomTreeUpdater
DTU(&DT
, DomTreeUpdater::UpdateStrategy::Lazy
);
507 bool Changed
= false;
508 for (Function::iterator BI
= F
.begin(), BE
= F
.end(); BI
!= BE
;) {
509 BasicBlock
&BB
= *BI
++;
510 auto II
= BB
.getFirstNonPHIOrDbg()->getIterator();
511 auto IE
= BB
.getTerminator()->getIterator();
512 // Iterate until we reach the terminator instruction. tryToSplitCallSite
513 // can replace BB's terminator in case BB is a successor of itself. In that
514 // case, IE will be invalidated and we also have to check the current
516 while (II
!= IE
&& &*II
!= BB
.getTerminator()) {
517 CallBase
*CB
= dyn_cast
<CallBase
>(&*II
++);
518 if (!CB
|| isa
<IntrinsicInst
>(CB
) || isInstructionTriviallyDead(CB
, &TLI
))
521 Function
*Callee
= CB
->getCalledFunction();
522 if (!Callee
|| Callee
->isDeclaration())
525 // Successful musttail call-site splits result in erased CI and erased BB.
526 // Check if such path is possible before attempting the splitting.
527 bool IsMustTail
= CB
->isMustTailCall();
529 Changed
|= tryToSplitCallSite(*CB
, TTI
, DTU
);
531 // There're no interesting instructions after this. The call site
532 // itself might have been erased on splitting.
541 struct CallSiteSplittingLegacyPass
: public FunctionPass
{
543 CallSiteSplittingLegacyPass() : FunctionPass(ID
) {
544 initializeCallSiteSplittingLegacyPassPass(*PassRegistry::getPassRegistry());
547 void getAnalysisUsage(AnalysisUsage
&AU
) const override
{
548 AU
.addRequired
<TargetLibraryInfoWrapperPass
>();
549 AU
.addRequired
<TargetTransformInfoWrapperPass
>();
550 AU
.addRequired
<DominatorTreeWrapperPass
>();
551 AU
.addPreserved
<DominatorTreeWrapperPass
>();
552 FunctionPass::getAnalysisUsage(AU
);
555 bool runOnFunction(Function
&F
) override
{
559 auto &TLI
= getAnalysis
<TargetLibraryInfoWrapperPass
>().getTLI(F
);
560 auto &TTI
= getAnalysis
<TargetTransformInfoWrapperPass
>().getTTI(F
);
561 auto &DT
= getAnalysis
<DominatorTreeWrapperPass
>().getDomTree();
562 return doCallSiteSplitting(F
, TLI
, TTI
, DT
);
567 char CallSiteSplittingLegacyPass::ID
= 0;
568 INITIALIZE_PASS_BEGIN(CallSiteSplittingLegacyPass
, "callsite-splitting",
569 "Call-site splitting", false, false)
570 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass
)
571 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass
)
572 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass
)
573 INITIALIZE_PASS_END(CallSiteSplittingLegacyPass
, "callsite-splitting",
574 "Call-site splitting", false, false)
575 FunctionPass
*llvm::createCallSiteSplittingPass() {
576 return new CallSiteSplittingLegacyPass();
579 PreservedAnalyses
CallSiteSplittingPass::run(Function
&F
,
580 FunctionAnalysisManager
&AM
) {
581 auto &TLI
= AM
.getResult
<TargetLibraryAnalysis
>(F
);
582 auto &TTI
= AM
.getResult
<TargetIRAnalysis
>(F
);
583 auto &DT
= AM
.getResult
<DominatorTreeAnalysis
>(F
);
585 if (!doCallSiteSplitting(F
, TLI
, TTI
, DT
))
586 return PreservedAnalyses::all();
587 PreservedAnalyses PA
;
588 PA
.preserve
<DominatorTreeAnalysis
>();